package com.atgugui.springcloud.controller;

import com.atgugui.springcloud.entities.CommonResult;
import com.atgugui.springcloud.entities.Payment;
import com.atgugui.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
  private   PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

@Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.creat(payment);
        log.info("******插入结果{}",result);
        if(result >0){
            return  new CommonResult(200,"订单插入数据成功，端口号是："+serverPort);
        }
            return  new CommonResult(444,"订单插入数据失败");

    }


    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("******订单查询结果{}",payment);
        if(payment !=null){
            return  new CommonResult<Payment>(200,"订单查询数据成功，端口号是："+serverPort,payment);
        }
        return  new CommonResult(444,"订单查询数据失败");

    }

@GetMapping("/payment/discovery")
    public Object discovery(){
//服务清单列表
    List<String> services = discoveryClient.getServices();
    for(String service : services){
        log.info("****************服务名称:{}",service);
    }
//根据服务名称，获取实例
    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMNET-SERVICE");
    for(ServiceInstance instance : instances){

        log.info(instance.getServiceId() +"\t" + instance.getHost() +"\t" + instance.getPort() + "\t" + instance.getUri());
    }
    return discoveryClient;
}

  @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}
